package cn.cjxy.userms.controller;

import cn.cjxy.userms.entity.User;
import cn.cjxy.userms.service.UserService;
import cn.cjxy.userms.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 接收前端update.jsp传递过来的form表单数据，并执行修改操作
 * 修改完成跳转回list 重新查询数据
 */
@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
    UserService userService=new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        //防止乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //获取表单中的user
        int id = Integer.parseInt(req.getParameter("id"));
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Integer gender = Integer.valueOf(req.getParameter("gender"));
        Integer age = Integer.valueOf(req.getParameter("age"));
        String address = req.getParameter("address");
        //将user的信息存入到实体
        User user = new User(id,username,password,gender,age,address);
        //调用service方法执行修改
        int i = userService.updateUser(user); //判断新增成功与否
        if (i==1){//修改成功
            //返回list页面 让它重新加载数据
            resp.sendRedirect("/list");
        }else {
            //返回add.jsp页面
            resp.sendRedirect("/update.jsp");
        }
    }
}
